﻿package com.common.utils
{
	/*
	 * A collection of static methods for common math operations.
	*/
	
	public class Math2 
	{
		// Returns a random float
		public static function randFloat(min:Number,max:Number=NaN):Number 
		{
			if (isNaN(max)) 
			{ 
				max = min; 
				min = 0; 
			}
			return Math.random() * (max - min) + min;
		}
		
		// Returns a random integer
		public static function rand(min:Number,max:Number=NaN):int 
		{
			if (isNaN(max)) 
			{ 
				max = min; 
				min = 0; 
			}
			return Math.floor(randFloat(min, max));
		}
		
		// Converts radians to degrees
		public static function toDeg(rad:Number):Number
		{
			return rad/Math.PI*180;
		}
		
		// Converts degrees to radians
		public static function toRad( deg:Number ):Number
		{
			return deg/180.0*Math.PI;
		}
		
		// Returns true or false based on chance
		public static function bool(chance:Number=0.5):Boolean
		{
			return (Math.random() < chance) ? true : false;
		}
		
		public static function getAngleOfElevationDegree(fromX:Number, fromY:Number, toX:Number, toY:Number) : Number{
			var returnAngle : Number = Math.atan2(toY - fromY, toX - fromX)/Math.PI * 180;
			returnAngle = convertTo180DegreeAngle(returnAngle);
			return returnAngle;
		}
		
		public static function convertTo180DegreeAngle(angle360 : Number) : Number{
			angle360 = normalizeAngle360(angle360);
			if(angle360 > 180)
				angle360 = angle360 - 360;
			return angle360;
		}
		
		public static function normalizeAngle360(angle360 : Number) : Number{
			while(angle360 >= 360)
				angle360 = angle360 % 360;
			return angle360;
		}
		
		public static function getChangeInAngle(toAngle180:Number, fromAngle180 : Number, radians : Boolean = false){
			var returnAngle : Number;
			returnAngle = toAngle180 - fromAngle180;
			if(!radians){
				if(returnAngle > 180)
					returnAngle = returnAngle - 360;
				else
					if(returnAngle < -180)
						returnAngle = 360 - returnAngle;
//				while(returnAngle >= 360 || returnAngle <= -360)
//					returnAngle = returnAngle % 360;
			}
			else{
				throw new Error("not implemented");
			}
			return returnAngle;
		}
		
		public static function convertTo360DegreeAngle(angle180 : Number) : Number{
			if(angle180 < 0){
				angle180 += 360;			
			}
			return angle180;
		}
		
		public static function getDistance(x1:Number, y1:Number, x2:Number, y2:Number) : Number{
			return Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));
		}
	}
}
